# -*- coding:utf-8 -*-
from flask import render_template, g, redirect, request, session, current_app, abort

from . import profile_blu
from ... import db, constants
from ...libs.qiniuyun.image_storage import storage
from ...models import News, User
from ...utils.common import get_user_info, get_category_info
from ...utils.resonse import info_jsonfy
from ...utils.response_code import RET
from ...utils.utils import random_uuid


@profile_blu.route("/info")
@get_user_info
def user_info():
    """用户页面"""
    user = g.user
    data = {
        "user": user.to_dict()
    }

    return render_template("news/user.html", data=data)


@profile_blu.route("/base_info", methods=["GET", "POST"])
@get_user_info
def base_info():
    """基本资料"""
    user = g.user
    if request.method == "GET":
        data = {
            "user": user.to_dict()
        }
        return render_template("news/user_base_info.html", data=data)
    else:
        # 校验参数
        data_dict = request.json
        signature = data_dict.get("signature")
        nickName = data_dict.get("nick_name")
        gender = data_dict.get("gender")

        if not gender:
            return info_jsonfy(RET.PARAMERR, "性别不能为空")
        if gender not in ["MAN", "WOMAN"]:
            return info_jsonfy(RET.PARAMERR, "性别参数不正确")

        user.gender = gender
        if nickName:
            user.nick_name = nickName
        if signature:
            user.signature = signature

        session["nickName"] = nickName

        data = user.to_dict()

        return info_jsonfy(RET.OK, "用户基本资料修改成功", data)


@profile_blu.route("/pic_info", methods=["GET", "POST"])
@get_user_info
def pic_info():
    """头像设置"""
    user = g.user
    if request.method == "GET":
        data = {
            "user": user.to_dict()
        }
        return render_template("news/user_pic_info.html", data=data)
    else:
        # 校验参数
        try:
            file = request.files.get("avatar").read()
        except Exception as e:
            current_app.logger.error(e)
            return info_jsonfy(RET.PARAMERR, "参数错误")

        # 上传至七牛云
        fileUrl = storage(file)
        if not fileUrl:
            return info_jsonfy(RET.THIRDERR, "上传失败")
        user.avatar_url = fileUrl
        data = {
            "user": user.to_dict()
        }
        return info_jsonfy(RET.OK, "上传成功", data)


@profile_blu.route("/user_follow")
@get_user_info
def user_follow():
    """我的关注"""
    user = g.user
    currentPage = request.args.get("current_page", 1)
    limit = request.args.get("limit", constants.USER_FOLLOWED_MAX_COUNT)
    try:
        currentPage = int(currentPage)
        limit = int(limit)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.PARAMERR, "参数错误")
    try:
        paginate = user.followed.paginate(currentPage, limit, False)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.DBERR, "数据库查询错误")
    currentPage = paginate.page
    totalPage = paginate.pages
    users = paginate.items
    users = [u.to_dict() for u in users]
    data = {
        "current_page": currentPage,
        "total_page": totalPage,
        "users": users
    }

    return render_template("news/user_follow.html", data=data)


@profile_blu.route("/other_info")
@get_user_info
def other_info():
    """作者信息"""
    user = g.user
    authorId = request.args.get("user_id")
    if not authorId:
        abort(404)
    authorObj = None
    try:
        authorObj = User.query.get(authorId)
    except Exception as e:
        current_app.logger.error(e)
    if not authorObj:
        abort(404)

    isFollowed = False
    if authorObj in user.followed:
        isFollowed = True
    data = {
        "author": authorObj.to_dict(),
        "is_followed": isFollowed,
        "user": user.to_dict()
    }
    return render_template("news/other.html", data=data)


@profile_blu.route("/other_news_list")
@get_user_info
def other_news_list():
    """分页查询当前作者发布的新闻数据"""
    currentPage = request.args.get("current_page", 1)
    limit = request.args.get("limit", constants.OTHER_NEWS_PAGE_MAX_COUNT)
    try:
        currentPage = int(currentPage)
        limit = int(limit)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.PARAMERR, "参数错误")
    authorId = request.args.get("user_id")
    if not authorId:
        return info_jsonfy(RET.PARAMERR, "参数错误")
    try:
        authorObj = User.query.get(authorId)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.DBERR, "数据库查询错误")
    if not authorObj:
        return info_jsonfy(RET.NODATA, "用户不存在")

    try:
        paginate = authorObj.news_list.paginate(currentPage, limit, False)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.DBERR, "数据库查询错误")
    newsListObj = paginate.items
    currentPage = paginate.page
    totalPage = paginate.pages
    newsList = [news.to_basic_dict() for news in newsListObj]
    data = {
        "current_page": currentPage,
        "total_page": totalPage,
        "news_list": newsList
    }
    return info_jsonfy(RET.OK, "success", data)


@profile_blu.route("/pass_info", methods=["GET", "POST"])
@get_user_info
def pass_info():
    """密码修改"""
    user = g.user
    if request.method == "GET":
        return render_template("news/user_pass_info.html")
    else:
        # 校验参数
        data_dict = request.json
        oldPassword = data_dict.get("old_password")
        newPassword = data_dict.get("new_password")

        if not all([oldPassword, newPassword]):
            return info_jsonfy(RET.PARAMERR, "参数错误")

        if not user.check_password(oldPassword):
            return info_jsonfy(RET.PARAMERR, "原密码不正确")

        if user.check_password(newPassword):
            return info_jsonfy(RET.PARAMERR, "新密码与原密码不能相同")

        user.password = newPassword

        return info_jsonfy(RET.OK, "密码修改成功")


@profile_blu.route("/user_collection")
@get_user_info
def user_collection():
    """我的收藏"""
    user = g.user
    # 校验参数
    currentPage = request.args.get("currentPage", 1)
    limit = request.args.get("limit", constants.USER_COLLECTION_MAX_NEWS)

    try:
        currentPage = int(currentPage)
        limit = int(limit)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.PARAMERR, "参数错误")

    try:
        paginate = user.collection_news.paginate(currentPage, limit, False)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.DBERR, "数据库查询错误")

    collectionNewsObj = paginate.items
    currentPage = paginate.page
    totalPage = paginate.pages

    collectionsNews = [news.to_review_dict() for news in collectionNewsObj]

    data = {
        "collections": collectionsNews,
        "current_page": currentPage,
        "total_page": totalPage,
    }

    return render_template("news/user_collection.html", data=data)


@profile_blu.route("/news_release", methods=["GET", "POST"])
@get_user_info
@get_category_info
def news_release():
    """新闻发布"""
    user = g.user

    if request.method == "GET":
        categories = g.categoryList
        for cate in categories:
            if cate.get("name") == "最新":
                categories.remove(cate)
                break

        if request.method == "GET":
            return render_template("news/user_news_release.html", data={"categories": categories})
    else:
        title = request.form.get("title")
        source = "个人发布"
        digest = request.form.get("digest")
        content = request.form.get("content")
        index_image = request.files.get("index_image")
        category_id = request.form.get("category_id")

        if not all([title, source, digest, content, index_image, category_id]):
            return info_jsonfy(RET.PARAMERR, "参数有误")

        try:
            index_image = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return info_jsonfy(RET.PARAMERR, "新闻首页图片参数有误")

        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return info_jsonfy(RET.THIRDERR, "上传图片错误")

        news = News()
        news.id = random_uuid()
        news.title = title
        news.digest = digest
        news.source = source
        news.content = content
        news.index_image_url = key
        news.category_id = category_id
        news.user_id = user.id
        news.status = 1

        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return info_jsonfy(RET.DBERR, "数据库保存失败")

        return info_jsonfy(RET.OK, "发布成功，等待审核")


@profile_blu.route("/news_list")
@get_user_info
def news_list():
    """我的发布"""
    user = g.user
    # 校验参数
    currentPage = request.args.get("currentPage", 1)
    limit = request.args.get("limit", constants.USER_COLLECTION_MAX_NEWS)

    try:
        currentPage = int(currentPage)
        limit = int(limit)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.PARAMERR, "参数错误")

    try:
        paginate = user.news_list.paginate(currentPage, limit, False)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.DBERR, "数据库查询错误")

    userNewsObj = paginate.items
    currentPage = paginate.page
    totalPage = paginate.pages

    userNewsList = [news.to_review_dict() for news in userNewsObj]

    data = {
        "current_page": currentPage,
        "total_page": totalPage,
        "news_list": userNewsList
    }

    return render_template("news/user_news_list.html", data=data)
